<?php
/**
 * Database abstraction class.
 * Works with SQLite only at the moment.
 */
class AtbudgetDB extends SQLite3 {
	function __construct($fname)
	{
		$this->open($fname);
		$this->busyTimeout(2000);
	}
}

	$db = new AtbudgetDB('../atbudget.sqlite');
	try {
		switch ($_SERVER['REQUEST_METHOD']) {
			case 'GET': //list transactions
				header('Content-type: application/json');
				if (isset($_GET['filter'])) {
					$filters = json_decode($_GET['filter']);
					$accid = $filters[0]->value;
					$res = $db->query('SELECT * FROM `transaction` WHERE fromaccount='.intval($accid).' OR toaccount='.intval($accid).' ORDER BY `timestamp` DESC');
					$transactions = array();
					if ($res) {
						while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
							if ($row['fromaccount'] != 0 ) {
								$fromacc = $db->query('SELECT * FROM `account` WHERE id='.intval($row['fromaccount']));
								$row['fromaccount'] = $fromacc->fetchArray(SQLITE3_ASSOC);
							}
							if ($row['toaccount'] != 0 ) {
								$toacc = $db->query('SELECT * FROM `account` WHERE id='.intval($row['toaccount']));
								$row['toaccount'] = $toacc->fetchArray(SQLITE3_ASSOC);
							}
							if ($row['category'] != 0 ) {
								$cat = $db->query('SELECT * FROM `category` WHERE id='.intval($row['category']));
								$row['category'] = $cat->fetchArray(SQLITE3_ASSOC);
								if ($row['category']['parentid'] != 0) {
									$parentcat = $db->query('SELECT * FROM `category` WHERE id='.intval($row['category']['parentid']));
									$row['category']['parent'] = $parentcat->fetchArray(SQLITE3_ASSOC);
								}
							}
							if ($row['payee'] != 0 ) {
								$payee = $db->query('SELECT * FROM `payee` WHERE id='.intval($row['payee']));
								$row['payee'] = $payee->fetchArray(SQLITE3_ASSOC);
							}
							$transactions[] = $row;
						}
					}
					echo json_encode(array('success' => 'true', 'transactions' => $transactions));
				} else {
					echo json_encode(array('success' => 'true', 'msg' => 'For security and performance reasons you cannot request all transactions at once. You have to specify account.','transactions' => array()));
				}
				break;
			case 'POST': //new transaction
				header('Content-type: application/json');
				$tx = json_decode($HTTP_RAW_POST_DATA);
				$tx->timestamp = strtotime($tx->timestamp);
				$fromacc = $tx->fromaccount ? $tx->fromaccount->id : 0;
				$toacc   = $tx->toaccount   ? $tx->toaccount->id   : 0;
				$sqlStr = 'INSERT INTO `transaction` (`timestamp`,`amount`,`fromaccount`,`toaccount`,`category`,`payee`,`rate`) VALUES ('.$tx->timestamp.','.$tx->amount.','.$fromacc.','.$toacc.','.$tx->category->id.','.$tx->payee->id.','.$tx->rate.')'; 
				if ($db->exec($sqlStr)) {
					$tx->id = $db->lastInsertRowID();
					echo json_encode(array('success' => 'true','transactions' => array($tx)));
				} else {
					echo json_encode(array('success' => 'false', 'msg' => 'Failed to create record.', 'transactions' => array()));
				}
				break;
			case 'PUT': //save transaction
				header('Content-type: application/json');
				echo json_encode(array('success' => 'false', 'msg' => 'Not implemented yet.', 'transactions' => array()));
				break;
			case 'DELETE': //delete transaction
				header('Content-type: application/json');
				echo json_encode(array('success' => 'false', 'msg' => 'Not implemented yet.', 'transactions' => array()));
				break;
			default:
				header('Content-type: application/json');
				echo json_encode(array('success' => 'false', 'msg' => 'Server cannot handle your request.','transactions' => array()));
		}//switch
	} catch (Exception $e) {
		header('Content-type: application/json');
		echo json_encode(array('success' => 'false', 'msg' => "Exception occurred.\n"+$e->getMessage(), 'transactions' => array()));
	}
	$db->close();
